import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {TicketService} from '../../../../services/api/ticket.service';
import {DynamicComponent, DynamicComponentEvent} from '../../../../../ng-tools';
import {HttpParams} from '@angular/common/http';

@Component({
  selector: 'personal-group-edit',
  templateUrl: './personal-group-edit.component.html',
  styleUrls: ['./personal-group-edit.component.scss']
})
export class PersonalGroupEditComponent implements OnInit, DynamicComponent {
  context: any;
  dynamic: true;
  events: DynamicComponentEvent;
  currentGroup;
  personalGroupForm: FormGroup;
  @Output() success = new EventEmitter();
  set data(value: any) {
    this.currentGroup = value;
  }
  constructor(private formBuilder: FormBuilder,
              private ticketService: TicketService) {
    this.personalGroupForm = this.formBuilder.group({
      gId: ['', Validators.required],
      masterFlPerc: ['', Validators.required],
    });
  }

  ngOnInit() {
    this.personalGroupForm.patchValue({
      gId: this.currentGroup.gid,
      masterFlPerc: this.currentGroup.master_fl_perc,
    });
  }
  trigger(eventName: string, ...args) {
    this[eventName].emit(...args);
    if (eventName in this.events) {
      this.events[eventName](...args);
    }
  }
  update() {
    if (this.personalGroupForm.valid) {
      this.ticketService.post(this.ticketService.urls.updateMasterFlPerc, this.personalGroupForm.value, {
        observe: 'response',
        params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
        if (resp.body.success) {
          this.trigger('success', this.personalGroupForm.value);
        }
      });
    }
  }
}
